/**
 * @author Tom Meyer
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Basic Tibetan web browser, which converts Tibetan text on the fly between 
 * Unicode and GB/T20524-2006 encodings.
 *    
 * Jan 16 2010, Initial creation, proof of concept
 * Jan 24 2010, Added URL choosing and pop-up menu
 * Jan 29 2010, Filtered out non-HTML types
 *              
 * TODO: proper documentation and unit tests
 * TODO: create Tibetan error web page
 * TODO: create Tibetan "home page"
 * TODO: user-defined home page
 * TODO: bookmarks (can we access bookmarks from built-in browser?
 * TODO: make it look more like the built-in web browser (url entry scrolls
 *       down from top, etc)
 *
 */

package com.kunzang;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;


public class SharChe extends Activity {
	final int MENU_URLENTRY = 0;
	final int MENU_BACK = 1;
	final int MENU_REFRESH = 2;
	final int MENU_QUIT = 3;
	final int MENU_FORWARD = 4;
	final int MENU_ABOUT = 5;
	
	WebView webview;
	TableLayout urlBar;
	EditText gotoUrl;
	Button urlButton;
	
	protected static final String errorPage = "http://google.com";
	protected static final String homePage = "http://sites.google.com/site/chrisfynn2/tibetan_21-taras";

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        webview = (WebView) findViewById(R.id.webview);
        webview.setWebViewClient(new SharCheClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setBuiltInZoomControls(true);

        urlBar = (TableLayout)findViewById(R.id.UrlEntry);
        gotoUrl = (EditText)findViewById(R.id.goUrl);
        urlButton = (Button)findViewById(R.id.goUrlButton);
        urlButton.setOnClickListener(myUrlButtonOnClickListener);        
         
        displayUrl(homePage);
        
	}

    protected void displayUrl(String url) {
        try {
        	URL siteURL = new URL(url);
        	URLConnection uc = siteURL.openConnection();
        	
        	//        	Class type[] = {String.class};
        	Object content = uc.getContent();
        	String contentEncoding = uc.getContentEncoding();
        	String contentType = uc.getContentType();

        	if (contentType == null) {
        		contentType = URLConnection.guessContentTypeFromName(url);
        	} else {
        		if (contentEncoding == null) {
	        		int semi = contentType.indexOf(";");
	        		if (semi > -1) {
	        			String newContentType = contentType.substring(0, semi);

	        			String[] splits = contentType.split("charset=");
        				if (splits.length > 1) {
        					contentEncoding = splits[1];
        				}
            			contentType = newContentType;
        			}
        		}
        	}
        	
        	String data;
        	
        	// TODO handle things other than HTML here
        	if (content instanceof InputStream) {
        		if (contentType == null) {
        			contentType = URLConnection.guessContentTypeFromStream((InputStream)content);
        		}

        		String string;
        		StringBuilder outputBuilder = new StringBuilder();
        		BufferedReader reader =
        	          new BufferedReader(new InputStreamReader((InputStream)content));
        	    while (null != (string = reader.readLine())) {
        	        outputBuilder.append(string).append('\n');
        	    }
        		data = outputBuilder.toString();
        	} else {
        		data = "Invalid content type is: " + content.toString();
        	}
        	
        	// TODO: Are there other types of content and encoding that we'd like to 
        	// handle?  RTF, doc, text, etc?
    		if (contentType.equals("text/html") && contentEncoding.equals("utf-8")) {
    			data = TibConvert.convertUnicodeToPrecomposedTibetan(data);
    		}
    		
        	String baseURL = url.substring(0, url.lastIndexOf("/")+1);

        	webview.loadDataWithBaseURL(baseURL,  
        								data, contentType, contentEncoding, 
        								errorPage);
        } catch (Exception e) {
        	String data = "ERROR: " + e.toString() + "\n";
        	StackTraceElement[] ste = e.getStackTrace();
        	for (int i= 0; i< ste.length; i++) {
        		data += ste[i].toString() + "\n"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            ;
        	}
        	webview.loadDataWithBaseURL("", data, "text/html", "utf-8", errorPage);
        	System.out.println(e.toString());
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    private class SharCheClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     menu.add(0, MENU_URLENTRY, 0, R.string.str_URLbar);
     menu.add(0, MENU_BACK,  0, R.string.str_Back);
     menu.add(0, MENU_REFRESH,  0, R.string.str_Refresh);
     menu.add(0, MENU_QUIT,   0, R.string.str_Quit);
     menu.add(0, MENU_FORWARD,  0, R.string.str_Forward);
     menu.add(0, MENU_ABOUT,  0, R.string.str_About);
     
     return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		
		switch(item.getItemId())
		{
		case MENU_URLENTRY:
			toggleGotoVisibility();
		    break;
		case MENU_ABOUT:
			openAboutDialog();
			break;
		case MENU_QUIT:
			openExitDialog();
			break;
		case MENU_BACK:
			if(webview.canGoBack())
				webview.goBack();
			break;
		case MENU_REFRESH:
			webview.reload();
			break;
		case MENU_FORWARD:
			if(webview.canGoForward())
				webview.goForward();
		break;
		}
		return true;
    }
    
    void toggleGotoVisibility()
    {
    	if (urlBar.getVisibility() == View.GONE)
    	{
    		urlBar.setVisibility(View.VISIBLE);
    	}
    	else
    	{
    		urlBar.setVisibility(View.GONE);
    	}
    }
    
    
    private void openAboutDialog()
    {
    	AlertDialog.Builder adb = new AlertDialog.Builder(this);
    	adb.setTitle(R.string.str_About);
    	adb.setMessage(R.string.str_about_message);
    	adb.setPositiveButton(R.string.str_ok,
	       new DialogInterface.OnClickListener()
	       {
		        public void onClick(DialogInterface dialoginterface, int i)
		        {}
	       });	
    	adb.show();
    }
    
    private void openExitDialog()
    {
    	AlertDialog.Builder adb = new AlertDialog.Builder(this);
    	adb.setTitle(R.string.str_Quit);
    	adb.setMessage(R.string.str_quit_message);
    	adb.setNegativeButton(R.string.str_no,
	       new DialogInterface.OnClickListener()
	       {
		        public void onClick(DialogInterface dialoginterface, int i)
		        {}
	       });
    	adb.setPositiveButton(R.string.str_ok,
	       new DialogInterface.OnClickListener()
	       {
		        public void onClick(DialogInterface dialoginterface, int i)
		        { 
		        	finish();
		        }
	       });
    	adb.show();
    }
    
    private Button.OnClickListener myUrlButtonOnClickListener
     = new Button.OnClickListener()
    {
    	public void onClick(View v) {
	    	webview.loadUrl(gotoUrl.getText().toString());
	    }
    };
}
